package com.yao.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yao.common.exception.BusinessException;
import com.yao.sys.entity.dto.DictItemDto;
import com.yao.sys.mapper.DictItemMapper;
import com.yao.sys.mapper.sql.DictItemWrapper;
import com.yao.sys.service.DictItemService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * 字典编码表 接口实现
 *
 * @author autoCode
 * @version 1.0.0-SNAPSHOT
 * @date 2020-04-09
 */
@Service
public class DictItemServiceImpl extends ServiceImpl<DictItemMapper, DictItemDto> implements DictItemService {

    @Override
    @Transactional(isolation = Isolation.REPEATABLE_READ, rollbackFor = BusinessException.class)
    public void add(DictItemDto dto) {
        this.check(dto.getValue(), dto.getCode());

        if (!this.save(dto)) {
            throw new BusinessException("新增字典编码失败");
        }
    }

    @Override
    @Transactional(isolation = Isolation.REPEATABLE_READ, rollbackFor = BusinessException.class)
    public void modifyById(DictItemDto dto) {
        this.check(dto.getValue(), dto.getCode());

        if (!this.updateById(dto)) {
            throw new BusinessException("更新字典编码失败");
        }

    }

    private void check(String value, String code) {
        Wrapper<DictItemDto> query = DictItemWrapper.byCode(value, code);

        boolean present = Optional.ofNullable(this.getOne(query)).isPresent();

        if (present) {
            throw new BusinessException("已经存在的字典编码{}::{}", code, value);
        }

    }
}